package controllers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.google.common.base.Strings;
import com.google.common.io.Files;
import models.cms.CMSImage;
import models.cms.CMSPage;

import org.apache.commons.lang.StringUtils;


import play.data.Form;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import play.mvc.With;


import javax.validation.Valid;

/*@With(Secure.class)
@Check("admin")*/
public class Admin extends Controller {
    static Form<CMSPage> form = form(CMSPage.class);
	public static Result index() {
		List<CMSPage> pages = CMSPage.find.all();
        return ok(views.html.Admin.index.render(pages));
	}

	public static Result editPage( String pageName) {
		CMSPage page = CMSPage.find.byId(pageName);
        return ok(views.html.Admin.edit.render(form.fill(page),pageName));
	}

	public static Result addPage() {
		CMSPage page = new CMSPage();
        return ok(views.html.Admin.edit.render(form.fill(page),""));
	}

    public static Result saveNewPage(){
        return savePage("");
    }

    public static Result savePage(String pageName) {
        Form<CMSPage> pageForm= form.bindFromRequest();
        CMSPage cmsPage = pageForm.get();
        if (!Strings.isNullOrEmpty(pageName) && pageForm.data().containsKey("delete")) {

            cmsPage.delete();
			return index();
		}
        if (Strings.isNullOrEmpty(pageName))
            cmsPage.save();
        else
        {
            CMSPage oldPage=CMSPage.find.byId(pageName);
            //oldPage.name=cmsPage.name;
            oldPage.body=cmsPage.body;
            oldPage.title=cmsPage.title;
            oldPage.update();
        }

		if (pageForm.data().containsKey("savePage"))
			return Frontend.show(cmsPage.name);
		return index();
	}

	public static Result upload() {
        Http.MultipartFormData multipartFormData = request().body().asMultipartFormData();
        CMSImage image = new CMSImage();
        Http.MultipartFormData.FilePart data = multipartFormData.getFile("data");
        image.name = data.getFilename();
        String[] title = multipartFormData.asFormUrlEncoded().get("title");

        if (title==null || title.length<1 || Strings.isNullOrEmpty(title[0]))
              image.title = image.name;
          else
              image.title = title[0];


        image.contentType=data.getContentType();

		try {
            image.data=Files.toByteArray(data.getFile());
		} catch (IOException e) {
			e.printStackTrace();
		}
		image.save();
        return redirect("/public/tiny_mce/plugins/advimage/image.htm");

	}

	public static Result imagelist() {
		List<CMSImage> images = CMSImage.find.all();
		return ok(views.html.Admin.imagelist.render(images)).as("application/javascript");
	}
}
